package com.wuyan.locationdog.ui.device


import android.graphics.BitmapFactory
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import androidx.activity.viewModels
import com.arcsoft.commonbase.base.BaseBindingActivity
import com.arcsoft.commonbase.bean.DogFileBeanContent
import com.arcsoft.commonbase.bus.Bus
import com.arcsoft.commonbase.bus.bus_device_info_modify
import com.arcsoft.commonbase.bus.bus_dog_file_info
import com.arcsoft.commonbase.ext.ImageOptions
import com.arcsoft.commonbase.ext.btnEnable
import com.arcsoft.commonbase.ext.fileToPart
import com.arcsoft.commonbase.ext.loadImage
import com.arcsoft.commonbase.ext.loadImageCircleCar
import com.arcsoft.commonbase.ext.textStringTrim
import com.arcsoft.commonbase.widgets.dialog.CommonDialog
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.PathUtils
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.wuyan.locationdog.R
import com.wuyan.locationdog.databinding.DeviceAddInfoActivityBinding
import com.wuyan.locationdog.help.DogHelp
import com.wuyan.locationdog.help.LoginHelp
import com.wuyan.locationdog.help.saveBitmapToFile
import com.wuyan.locationdog.ui.my.MyModifyPhoneActivity
import com.wuyan.locationdog.util.imageselecter.GlideEngine
import com.wuyan.locationdog.util.imageselecter.ImageCropEngine
import com.wuyan.locationdog.view.DogAgePopup
import com.wuyan.locationdog.view.DogTypePopup
import com.wuyan.locationdog.view.ImgSelectPopup
import com.wuyan.locationdog.viewmodel.DeviceViewModel
import okhttp3.RequestBody
import java.io.File

class DogAddFilesActivity : BaseBindingActivity<DeviceAddInfoActivityBinding>(), TextWatcher {
    private val mViewModel: DeviceViewModel by viewModels()
    private var fileUrl: String? = null

    override fun initData() {
        setTitleText("猎犬档案")

        if (DogHelp.isModifyDogFile) {
            binding.apply {
                DogHelp.mDogFileBeanContent?.let {
                    fileUrl = DogHelp.mDogFileBeanContent?.dogImg.toString()

                    dogImg.loadImageCircleCar(it.dogImg)

                    dogName.setText(it.dogName)
                    dogType.text = it.dogType
                    age.text = it.age
                    weight.setText(it.weight)
                    remark.setText(it.remark)
                    if (it.gender == "公") {
                        rb1.isChecked = true
                        rb2.isChecked = false
                    } else {
                        rb1.isChecked = false
                        rb2.isChecked = true
                    }
                    afterTextChanged(null)
                }
            }

        }
        binding.apply {
            dogName.addTextChangedListener(this@DogAddFilesActivity)
            weight.addTextChangedListener(this@DogAddFilesActivity)

            radiogroup.setOnCheckedChangeListener { group, checkedId ->

                rb1.isChecked = rb1.isChecked
                rb2.isChecked = rb2.isChecked

            }
            btnDogType.setOnClickListener {
                DogTypePopup(mActivity) {
                    dogType.text = it
                }.showPopupWindow()
            }
            btnAge.setOnClickListener {
                DogAgePopup(mActivity) { age.text = it }.showPopupWindow()

            }
            btnPhone.setOnClickListener {
                ActivityUtils.startActivity(MyModifyPhoneActivity::class.java)
            }
            btnPhoto.setOnClickListener {
                ImgSelectPopup(mActivity).apply {
                    showPopupWindow()
                    findViewById<View>(R.id.btnPhoto).setOnClickListener {
                        dismiss()
                        PictureSelector.create(mActivity)
                            .openGallery(SelectMimeType.ofImage())
                            .setImageEngine(GlideEngine())
                            .setCropEngine(ImageCropEngine())
                            .setMaxSelectNum(1)
                            .forResult(object : OnResultCallbackListener<LocalMedia> {
                                override fun onResult(result: ArrayList<LocalMedia>) {
                                    val file = File(result[0].availablePath)
                                    dogImg.loadImageCircleCar(result[0].availablePath)
                                    val map = HashMap<String, RequestBody>()
                                    mViewModel.fileUpload(map, fileToPart(file))
                                }

                                override fun onCancel() {}
                            })


                    }
                    findViewById<View>(R.id.btnCamera).setOnClickListener {
                        dismiss()

                        PictureSelector.create(mActivity)
                            .openCamera(SelectMimeType.ofImage())
                            .setCropEngine(ImageCropEngine())
                            .forResult(object : OnResultCallbackListener<LocalMedia> {
                                override fun onResult(result: ArrayList<LocalMedia>) {
                                    val file = File(result[0].availablePath)
                                    dogImg.loadImageCircleCar(result[0].availablePath)

                                    val map = HashMap<String, RequestBody>()
                                    mViewModel.fileUpload(map, fileToPart(file))
                                }

                                override fun onCancel() {}
                            })

                    }
                    findViewById<View>(R.id.btnDefault).setOnClickListener {
                        val bitmap = BitmapFactory.decodeResource(
                            context.getResources(),
                            com.arcsoft.commonbase.R.mipmap.def_dog
                        )

                        saveBitmapToFile(PathUtils.getInternalAppCachePath(), bitmap, "default.png")

                        val map = HashMap<String, RequestBody>()
                        val file = File(PathUtils.getInternalAppCachePath() + "/default.png")
                        dogImg.setImageBitmap(bitmap)

                        mViewModel.fileUpload(map, fileToPart(file))
                    }
                }

            }

            btnSure.setOnClickListener {
                //{
                //  "age": "string",
                //  "dogId": 0,
                //  "dogImg": "string",
                //  "dogName": "string",
                //  "dogType": "string",
                //  "gender": "string",
                //  "remark": "string",
                //  "weight": 0
                //}
                CommonDialog(mActivity, title = "确定提交吗？", "") {

                    val map = HashMap<String, Any>()
                    map["dogName"] = dogName.textStringTrim()
                    map["age"] = age.textStringTrim()
                    map["dogType"] = dogType.textStringTrim()
                    map["gender"] = if (rb1.isChecked) "公" else "母"
                    map["weight"] = weight.textStringTrim()
                    map["remark"] = remark.textStringTrim()
                    map["dogImg"] = fileUrl.toString()

                    if (LoginHelp.isFromLogin) {
                        val firstBean = DogFileBeanContent(
                            true,
                            age.textStringTrim(),
                            "",
                            "first",
                            fileUrl.toString(),
                            dogName.textStringTrim(),
                            dogType.textStringTrim(),
                            if (rb1.isChecked) "公" else "母",
                            false,
                            false,
                            remark.textStringTrim(),
                            weight.textStringTrim()
                        )
                        Bus.post(bus_dog_file_info, firstBean)
                        finish()
                        return@CommonDialog
                    }

                    if (DogHelp.isModifyDogFile) {
                        map["dogId"] = DogHelp.mDogFileBeanContent?.dogId.toString()
                        mViewModel.updateDog(map)
                    } else {
                        mViewModel.addDog(map)
                    }
                }.show()

            }
        }


    }

    override fun observe() {
        super.observe()
        mViewModel.fileUploadBean.observe(this) {
            fileUrl = it.content.fileUrl

        }
        mViewModel.anyBean.observe(this) {
            Bus.post(bus_device_info_modify, "")
            finish()
        }

    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {


    }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

    }

    override fun afterTextChanged(s: Editable?) {
        binding.apply {
            btnEnable(btnSure, dogName)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        DogHelp.isModifyDogFile = false

    }
}